package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.PlatformFForum;
import com.ruoyi.teaching.domain.PlatformFLike;
import com.ruoyi.teaching.domain.UniversalCreateUpdate;
import com.ruoyi.teaching.domain.vo.PlatformFForumVO;
import com.ruoyi.teaching.domain.vo.PlatformFLikeVO;
import com.ruoyi.teaching.mapper.PlatformFForumMapper;
import com.ruoyi.teaching.mapper.PlatformFLikeMapper;
import com.ruoyi.teaching.service.PlatformFLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-10-14
 */
@Service
public class PlatformFLikeServiceImpl extends ServiceImpl<PlatformFLikeMapper, PlatformFLike> implements PlatformFLikeService {

    @Autowired
    private PlatformFLikeMapper likeMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private PlatformFForumMapper platformFForumMapper;

    @Override
    public AjaxResult addForumComment(Long objectId) {
        // 获取当前用户信息
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(userMapper);
        Long userId = Long.valueOf(update.getId());

        // 先检查内容是否存在
        PlatformFForum platformFForum = platformFForumMapper.selectById(objectId);
        if (platformFForum == null) {
            return AjaxResult.error("当前内容不存在");
        }

        // 检查是否已经点赞（不需要加锁）
        QueryWrapper<PlatformFLike> likeQueryWrapper = new QueryWrapper<>();
        likeQueryWrapper.eq("object_id", objectId);
        likeQueryWrapper.eq("create_id", update.getId());
        List<PlatformFLike> platformFLikeList = likeMapper.selectList(likeQueryWrapper);
        if (CollectionUtils.isNotEmpty(platformFLikeList)) {
            return new AjaxResult(HttpStatus.SUCCESS, "点赞成功");
        }

        // 锁定用户 ID，防止重复点赞的并发问题
        synchronized (userId.toString().intern()) {
            // 再次检查是否已点赞，防止在获取锁前其他线程已经执行了点赞操作
            List<PlatformFLike> platformFLikeListAfterLock = likeMapper.selectList(likeQueryWrapper);
            if (CollectionUtils.isNotEmpty(platformFLikeListAfterLock)) {
                return new AjaxResult(HttpStatus.SUCCESS, "点赞成功");
            }

            // 新增点赞记录
            PlatformFLike platformFLike = new PlatformFLike();
            platformFLike.setObjectId(objectId);
            platformFLike.setLikeToId(Long.valueOf(platformFForum.getCreateId()));
            platformFLike.setLikeType(platformFForum.getTopId() == null ? 0 : 1);
            platformFLike.setCreateBy(update.getName());
            platformFLike.setCreateTime(DateUtils.getNowDate());
            platformFLike.setCreateId(update.getId());
            int i = likeMapper.insert(platformFLike);
            if (i > 0) {
                // 修改帖子表点赞总数
                QueryWrapper<PlatformFLike> platformFLikeQueryWrapper = new QueryWrapper<>();
                platformFLikeQueryWrapper.eq("object_id", objectId);
                List<PlatformFLike> platformFLikes = likeMapper.selectList(platformFLikeQueryWrapper);
                PlatformFForum platformFForumUpdate = new PlatformFForum();
                platformFForumUpdate.setId(objectId);
                platformFForumUpdate.setLikeNum(platformFLikes.size());
                platformFForumMapper.updateById(platformFForumUpdate);
                return new AjaxResult(HttpStatus.SUCCESS, "点赞成功");
            } else {
                return new AjaxResult(HttpStatus.ERROR, "点赞失败");
            }
        }
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult delete(Long[] ids) {
        int i1 = likeMapper.deleteBatchIds(Arrays.asList(ids));
        if (i1 == ids.length) {
            // 修改帖子表点赞总数
            for (Long id : ids) {
                QueryWrapper<PlatformFLike> platformFLikeQueryWrapper = new QueryWrapper<>();
                platformFLikeQueryWrapper.eq("object_id", id);
                List<PlatformFLike> platformFLikes = likeMapper.selectList(platformFLikeQueryWrapper);
                PlatformFForum platformFForum1 = new PlatformFForum();
                platformFForum1.setId(id);
                platformFForum1.setLikeNum(platformFLikes.size());
                platformFForumMapper.updateById(platformFForum1);
                return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
            }
        }
        throw new RuntimeException("删除失败");
    }

    @Override
    public AjaxResult deleteLikeComment(Long[] ids) {
        int i = 0;
        for (Long id : ids) {
            UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(userMapper);
            QueryWrapper<PlatformFLike> likeQueryWrapper = new QueryWrapper<>();
            likeQueryWrapper.eq("object_id", id);
            likeQueryWrapper.eq("create_id", update.getId());
            int delete = likeMapper.delete(likeQueryWrapper);
            if (delete > 0) {
                // 修改帖子表点赞总数
                QueryWrapper<PlatformFLike> platformFLikeQueryWrapper = new QueryWrapper<>();
                platformFLikeQueryWrapper.eq("object_id", id);
                List<PlatformFLike> platformFLikes = likeMapper.selectList(platformFLikeQueryWrapper);
                PlatformFForum platformFForum1 = new PlatformFForum();
                platformFForum1.setId(id);
                platformFForum1.setLikeNum(platformFLikes.size());
                platformFForumMapper.updateById(platformFForum1);
                i++;
            }
        }
        if (i == ids.length) {
            return new AjaxResult(HttpStatus.SUCCESS, "取消点赞成功");
        }
        throw new RuntimeException("取消点赞失败");
    }

    @Override
    public AjaxResult getPersonalLikeList(Integer pageNum, Integer pageSize, Integer type) {
        // 初始化分页对象
        Page<PlatformFLike> platformFLikePage = new Page<>(pageNum, pageSize);

        // 构建查询条件，根据 type 参数判断是按 create_id 还是 like_to_id 筛选
        QueryWrapper<PlatformFLike> likeQueryWrapper = new QueryWrapper<>();
        Long userId = SecurityUtils.getUserId();
        likeQueryWrapper.eq(type != null ? (type == 0 ? "create_id" : "like_to_id") : "create_id", userId)
                .orderByDesc("create_time"); // 按照 create_time 降序排列

        // 执行分页查询
        platformFLikePage = likeMapper.selectPage(platformFLikePage, likeQueryWrapper);

        // 初始化 VO 分页对象
        Page<PlatformFLikeVO> platformFLikeVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(platformFLikePage, platformFLikeVOPage);

        // 循环处理查询结果，填充 PlatformFLikeVO 对象
        List<PlatformFLikeVO> likeVOList = new ArrayList<>();
        for (PlatformFLike record : platformFLikePage.getRecords()) {
            // 查询点赞的对象（帖子或评论）
            PlatformFForum platformFForum = platformFForumMapper.selectById(record.getObjectId());
            PlatformFLikeVO platformFLikeVO = new PlatformFLikeVO();

            // 复制基础数据到 VO 对象
            BeanUtils.copyProperties(record, platformFLikeVO);
            if (null == type) {
                type = 0;
            } else if (type > 1) {
                type = 0;
            }

            if (platformFForum != null) {
                // 若点赞对象为帖子/评论，设置点赞对象的创建者名称
                String myCreate = platformFForum.getCreateBy();
                String forMe = record.getCreateBy();
                String message = platformFForum.getMessage();
                if (Math.toIntExact(userId) == record.getCreateId()) {
                    forMe = "我";
                }
                if (Math.toIntExact(userId) == platformFForum.getCreateId()) {
                    myCreate = "我";
                }
                platformFLikeVO.setLikeToName(myCreate);

                // 根据点赞类型（0: 帖子, 1: 评论）设置对应的标题或内容

                if (record.getLikeType() == 0) {
                    platformFLikeVO.setCommentTitle(type == 0 ? "我点赞了" + myCreate + "发布的帖子：" + message : forMe + "点赞了我发布的帖子：" + message); // 帖子标题
                } else {
                    platformFLikeVO.setCommentTitle(type == 0 ? "我点赞了" + myCreate + "发布的评论：" + message : forMe + "点赞了我发布的评论：" + message); // 评论内容
                }
            } else {
                // 若点赞对象不存在，查询用户昵称
                SysUser user = userMapper.selectUserById(record.getLikeToId());
                String userName = "";
                if (user == null) {
                    userName = "用户不存在";
                    platformFLikeVO.setLikeToName(userName);
                } else {
                    if (Math.toIntExact(userId) == record.getCreateId()) {
                        userName = "我";
                    } else {
                        userName = record.getCreateBy();
                    }
                    platformFLikeVO.setLikeToName(user.getNickName());
                }
                // 根据点赞类型设置已删除的提示信息
                if (record.getLikeType() == 0) {
                    platformFLikeVO.setCommentTitle(type == 0 ? "我点赞了" + userName + "发布的帖子：" + "该帖子已被删除" : userName + "点赞了我发布的帖子：" + "该帖子已被删除");
                } else {
                    platformFLikeVO.setCommentTitle(type == 0 ? "我点赞了" + userName + "发布的评论：" + "该评论已被删除" : userName + "点赞了我发布的评论：" + "该评论已被删除");
                }
            }

            // 添加帖子信息
            PlatformFForum platformFForum1 = null;
            if (platformFLikeVO.getLikeType() == 0) {
                platformFForum1 = platformFForumMapper.selectById(platformFLikeVO.getObjectId());
            } else {
                PlatformFForum platformFForum2 = platformFForumMapper.selectById(platformFLikeVO.getObjectId());
                if (null != platformFForum2) {
                    platformFForum1 = platformFForumMapper.selectById(platformFForum2.getTopId());
                }
            }
            if (null != platformFForum1) {
                PlatformFForumVO platformFForumVO = new PlatformFForumVO();
                BeanUtils.copyProperties(platformFForum1, platformFForumVO);
                SysUser user = userMapper.selectUserById(Long.valueOf(platformFForum1.getCreateId()));
                if (null != user) {
                    if (null != user.getAvatar()) {
                        platformFForumVO.setCreateUrl(user.getAvatar());
                    }
                }
                String imageUrl = platformFForum1.getImageUrl();
                if (null != imageUrl && !imageUrl.equals("")) {
                    String[] imageUrls = imageUrl.split(",");
                    platformFForumVO.setImageUrl(imageUrls);
                }
                // 添加本人是否点赞信息
                Long userId1 = PlatformFForumServiceImpl.getCurrentUserId();
                // 设置点赞状态
                platformFForumVO.setIsLike(getUserLikeStatus(platformFForum1.getId(), userId1));

                // 查找当前帖子下的评论
                List<PlatformFForumVO> topLevelComments = getComment(Math.toIntExact(platformFForumVO.getId()));
                Page<PlatformFForumVO> page = PlatformFForumServiceImpl.toPage(topLevelComments, 1, 10, platformFForumVO);
                platformFForumVO.setChildrenPage(page);

                platformFLikeVO.setPlatformFForumVO(platformFForumVO);
            }

            likeVOList.add(platformFLikeVO); // 将处理后的 VO 添加到结果列表中
        }

        // 设置 VO 列表到分页对象中
        platformFLikeVOPage.setRecords(likeVOList);

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformFLikeVOPage);
    }

    /**
     * 获取用户对特定对象的点赞状态。
     *
     * @param objectId 点赞对象的 ID
     * @param userId   用户 ID
     * @return 如果用户已点赞则返回 1，否则返回 0
     */
    private int getUserLikeStatus(Long objectId, Long userId) {
        if (userId == null) {
            return 0;  // 如果用户未登录，返回未点赞状态
        }

        // 构建查询条件
        QueryWrapper<PlatformFLike> likeQueryWrapper = new QueryWrapper<>();
        likeQueryWrapper.eq("object_id", objectId);
        likeQueryWrapper.eq("create_id", userId);

        // 判断是否有点赞记录
        return likeMapper.selectCount(likeQueryWrapper) > 0 ? 1 : 0;
    }

    private List<PlatformFForumVO> getComment(Integer forumId) {
        // 构建查询条件，查询指定 forumId 的评论
        QueryWrapper<PlatformFForum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("top_id", forumId);

        // 获取所有符合条件的评论列表
        List<PlatformFForum> forums = platformFForumMapper.selectList(queryWrapper);
        List<PlatformFForumVO> forumVOList = new ArrayList<>();

        // 遍历评论，将 PlatformFForum 转换为 PlatformFForumVO，同时获取用户信息
        for (PlatformFForum forum : forums) {
            PlatformFForumVO forumVO = new PlatformFForumVO();
            BeanUtils.copyProperties(forum, forumVO);

            // 获取回复用户的昵称并设置到 VO 中
            SysUser replyUser = userMapper.selectUserById(forumVO.getReplyUserId());
            forumVO.setReplyUserName(replyUser != null ? replyUser.getNickName() : "用户不存在");

            SysUser user = userMapper.selectUserById(Long.valueOf(forumVO.getCreateId()));
            // 设置用户头像
            if (null != user) {
                if (null != user.getAvatar()) {
                    forumVO.setCreateUrl(user.getAvatar());
                }
            }

            // 添加本人是否点赞信息
            Long userId = PlatformFForumServiceImpl.getCurrentUserId();
            // 设置点赞状态
            forumVO.setIsLike(getUserLikeStatus(forum.getId(), userId));

            forumVOList.add(forumVO);
        }

        // 过滤出顶级评论（即没有 topCommentId 的评论）
        List<PlatformFForumVO> topLevelComments = forumVOList.stream()
                .filter(forumVO -> forumVO.getTopCommentId() == null)
                .collect(Collectors.toList());

        // 为每个顶级评论找到其子评论，并设置到 VO 的 children 属性中
        for (PlatformFForumVO topComment : topLevelComments) {
            List<PlatformFForumVO> childComments = forumVOList.stream()
                    .filter(forumVO -> forumVO.getTopCommentId() != null && forumVO.getTopCommentId().equals(topComment.getId()))
                    .collect(Collectors.toList());
            topComment.setChildren(childComments);
        }

        return topLevelComments;
    }

}
